package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.AddressDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.List;


@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private AddressDao addressDao;
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Address> addresses = addressDao.selectByCondition(queryString);
        long total = addresses.getTotal();
        List<Address> rows = addresses.getResult();
        return new PageResult(total,rows);
    }


    @Override
    public void add( Address address) {
        addressDao.add(address);
        String filename = address.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,filename);
    }

    @Override
    public Address findById(Integer id) {
        return addressDao.findById(id);
    }

    @Override
    public List<Address> findAll() {
        return addressDao.findAll();
    }

    @Override
    public void edit(Address address) {
        if (address!=null){
            Integer id = address.getId();
           Integer count = addressDao.findCountByAddressId(id);
            if (count!=null&&count>0){
                throw new RuntimeException("删除地址失败，有订单未完成");
            }
            addressDao.edit(address);
        }

    }

    @Override
    public void deleteById(Integer id) {
        Integer count = addressDao.findCountByAddressId(id);
        if (count!=null&&count>0){
            throw new RuntimeException("删除地址失败，有订单未完成");
        }
        addressDao.deleteById(id);
    }


}